package com.oak.designmode._07_proxyParttern.CGLibProxy;

import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * CglibProxy代理类
 *
 * @ClassName: CglibProxy
 * @Description  CglibProxy创建代理类性能高于动态代理，但是耗时更长，所以适用单例模式；实现Spring AOP的基础
 * @Author guoxy
 * @Date 2019/11/30
 * @Version 1.0
 */
public class CglibProxy implements MethodInterceptor {

    private Object target;

    public Object getInstance(Object target) {
        this.target = target;
        Enhancer enhancer = new Enhancer();
        enhancer.setSuperclass(this.target.getClass());
        enhancer.setCallback(this);
        return enhancer.create();
    }

    @Override
    public Object intercept(Object object, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {
        System.out.println("执行前的准备工作..");
        //调用（父类）业务类方法
        Object result = methodProxy.invokeSuper(object, args);
        System.out.println("执行完毕的善后工作...");
        return result;
    }
}